<!DOCTYPE html>
<title>Test media element's "played" attribute and range collapse.</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="video-played.js"></script>
<video></video>
<script>
var video;
async_test(function(t) {
    var expectedStartTimes = [];
    var expectedEndTimes = [];
    video = document.querySelector("video");

    video.oncanplay = t.step_func(function() {
        video.oncanplay = null;
        testRanges(expectedStartTimes, expectedEndTimes);
        // Test playing when there are no ranges.
        timeRangeCount = currentTimeRange = 0;
        video.currentTime = 0.5;
        currentTimeRange++;
        startPlayingInNewRange(t, expectedStartTimes);
    });
    waitForPauseAndContinue(t, createANewRange, false, expectedStartTimes, expectedEndTimes);

    function createANewRange() {
        // Create a new range.
        var newTime = (video.played.end(0) + 0.05).toFixed(2);
        video.currentTime = newTime;
        startPlayingInNewRange(t, expectedStartTimes);
        waitForPauseAndContinue(t, jumpAndCollapseTwoRanges, false, expectedStartTimes, expectedEndTimes);
    }

    function jumpAndCollapseTwoRanges() {
        // Test playing from one range into another, should collapse the two ranges.
        timeRangeCount--;
        currentTimeRange = timeRangeCount - 1;
        expectedStartTimes[0] = (expectedStartTimes[0] - 0.1).toFixed(2);
        expectedEndTimes[0] = expectedEndTimes[1];
        video.currentTime = expectedStartTimes[0];
        playForDuration(expectedEndTimes[1] - expectedStartTimes[0], t);
        waitForPauseAndContinue(t, testLoopingAndPassToTheEnd, false, expectedStartTimes, expectedEndTimes);
    }

    function testLoopingAndPassToTheEnd() {
        // Start playing near the end of the movie so it will loop quickly.
        video.loop = true;
        var startTime = (video.duration - 0.05).toFixed(2);
        video.currentTime = startTime;

        // We will end in the very first time range
        currentTimeRange = 0;

        // Playing from near the end so we will create a new time range from startTime, duration.
        timeRangeCount++;
        expectedStartTimes[timeRangeCount - 1] = startTime;
        expectedEndTimes[timeRangeCount - 1] = video.duration.toFixed(2);

        // Playback restarts from beginning, so expect the beginning of first time range to be 0.
        expectedStartTimes[0] = "0.00";
        // Have to play for long enough to loop and play into the existing range.
        playForDuration(1.25, t);
        waitForPauseAndContinue(t, null, true, expectedStartTimes, expectedEndTimes);
    }

    video.src = "content/test.ogv";
});
</script>